import React,{Component} from 'react'
import Pages from '../Pages'
import {Spin,message,Button} from 'antd'
import Layer from '../Layer'
import $ from 'jquery'
import * as pub from '../../config/public';
import * as fetch from '../../config/fetch';
import {Link,browserHistory} from 'react-router';
import Dropzone from 'react-dropzone';
class ImagItem extends Component {
     constructor(props) {
		super(props)
		this.state = {
			ImagItem:this.props.item,
			visibleDel:false,
			cover_imageBJ:this.props.cover_imageBJ?this.props.cover_imageBJ:[]
		}
	 }
	 componentWillReceiveProps(nextProps) {
		 this.setState({
			 cover_imageBJ:nextProps.cover_imageBJ
		 })
	 }
	 onMouseOver(){
       this.setState({
		   visibleDel:true
	   })
	}	
	onMouseOut(){
       this.setState({
		   visibleDel:false
	   })
	}
	// DeleteImg(value){
	// 	this.props.handleImg(value);
	// }
	DeleteImgPath(value,value1){
		if(value1){
          this.props.handleImgPath(value);
		}else{
          this.props.handleImg(value);  
		}
	}
	 render(){
		 return(
			 <div>
					 <li key={this.props.index} id={`image${this.props.index}`} onClick={()=>this.DeleteImgPath(this.props.index,this.props.item.essayPhotoPath)}><img src={this.props.item.essayPhotoPath?pub.getFile(this.props.item.essayPhotoPath):this.props.item.preview} onMouseOver={this.onMouseOver.bind(this)} onMouseOut={this.onMouseOut.bind(this)} alt="我的蜂行圈"/>
					     {this.state.visibleDel?
				                <span  className="trash" >删除</span>:null
			             }
					 </li>
			 </div>
		 )
	 }
}
class AddMessge extends Component {
	constructor(props) {
		super(props)
		this.state = {
			visible: false,
			inputValue:this.props.inputValue?this.props.inputValue:'',
			textareaValue:this.props.textareaValue?this.props.textareaValue:'',
            cover_image:[],
			visibleDel:false,
			essayId:this.props.essayId?this.props.essayId:'',
			cover_imageBJ:this.props.cover_imageBJ?this.props.cover_imageBJ:[],
			texts:this.props.texts,
			loadBtning:false,
			loadSaving:false
		}
	}
	componentWillReceiveProps(nextProps) {
			
			this.setState({
				visible:nextProps.modalShow,
				inputValue:nextProps.inputValue,
				textareaValue:nextProps.textareaValue,
				essayId:nextProps.essayId,
				cover_imageBJ:nextProps.cover_imageBJ,
				texts:nextProps.texts
			})

    }
	showModal = () => {
		this.setState({
			visible: true,
			texts:"新增文章",
			inputValue:'',
			textareaValue:'',
			cover_image:[],
			cover_imageBJ:[]
		});
	}
	hideMdoal = (e) => {
		$('.layer').addClass('layer-anim-close');
		setTimeout(() => {
			$('.layer').removeClass('layer-anim-close');
			this.setState({
				essayTitle:'',
				essayNote:'',
				cover_image:[],
				visible: false,
				essayId:'',
				loadBtning:false,
				loadSaving:false
			},()=>{
				this.props.loadList();
			});
		}, 50);
	}
	onSubmit = (value) => {

		let formData = new FormData();
		formData.append('essayTitle', this.state.inputValue);
		formData.append('essayNote', this.state.textareaValue);
		if (this.state.texts === '编辑文章') {
			formData.append('essayId', this.state.essayId);
		}
		formData.append('checkState', value);
		for (let x of this.state.cover_image) {
			formData.append('file', x);
		}
		for (let x of this.state.cover_imageBJ) {
			formData.append('photoPath', x.essayPhotoPath);
		}
		if (this.state.essayId !== "") {
			formData.append('operationState', 'U');
		}
		if (this.state.inputValue.replace(/^ +| +$/g, '') !== "" && this.state.textareaValue.replace(/^ +| +$/g, '') !== "") {
			pub.loading(this, true);
			if (value === 4) {
				this.setState({
					loadSaving: true
				});
			} else {
				pub.loadBtning(this, true);
			}
			fetch.insertorupdate(formData).then((data) => {
				pub.loading(this, false);
				pub.loadBtning(this, false);
				this.setState({loadSaving:false});
				this.setState({
					essayTitle: '',
					essayNote: '',
					cover_image: [],
					cover_imageBJ: [],
					visible: false,
					essayId: ''
				}, () => {
					this.props.loadList();
				})
			}, (res) => {
				pub.loading(this, false);
				pub.loadBtning(this, false);
				this.setState({loadSaving:false});
				pub.reject(res);
				this.setState({
					essayId: '',
					cover_image: [],
					cover_imageBJ: [],
				})
			})
		} else {
			message.error('不能输入空格', 3);
		}

	}
	inputValue=(event)=>{
		if( event.target.value.length>20){
			event.target.value="";
			message.warning('文章标题不能超过20字！')	
		}else{
            this.setState({inputValue: event.target.value});
		}
	}
	textareaValue=(event)=>{
       this.setState({textareaValue: event.target.value});
	}
	chooseImage(accepted, rejected){
		//if(this.state.texts==='新增消息'){
			if(accepted.length+this.state.cover_image.length+this.state.cover_imageBJ.length>9){
				message.error('图片不能超过9张')
			}else{
				this.setState({
					cover_image:this.state.cover_image.concat(accepted),
					//cover_imageBJ:[],
				})
			}
		// }else{
		// 	if(accepted.length>9){
		// 		message.error('图片不能超过9张')
		// 	}else{
		// 		this.setState({
		// 			cover_image:accepted,
		// 			// cover_imageBJ:[],
		// 		})
		// 	}
		// }
		
	}

	handleImg(value){
		let image = this.state.cover_image;
		let data = [];
		for(let i in image){
			if(Number(i) !== Number(value)){
				data.push(image[i])
			}
		}
		this.setState({
			cover_image:data
		})
	}
	handleImgPath(value){
		let image = this.state.cover_imageBJ;
		let data = [];
		for(let i in image){
			if(Number(i) !== Number(value)){
				data.push(image[i])
			}
		}
		this.setState({
			cover_imageBJ:data
		})
	}
	loadList(){
		this.setState({
			essayId:''
		},()=>{
            this.props.loadList();
		})
	}
	
	render(){
		return(
	    <div>
			<Layer
				title ={this.state.texts}
				show={this.state.visible}
				hide={()=>this.hideMdoal()}
				width="700px"
				height="500px"
			>
				<div className="layui-layer-content" style={{height:'407px'}}>

					<div className="row">
						<div className="pop-box-1">						  					
							    <dl className="pop-box-2">												
								<dt>文章标题：</dt>												
								   <dd>
									   <input value={this.state.inputValue}  maxLength="50" onChange={this.inputValue.bind()} placeholder="请输入文章标题" type="text" onKeyUp={this.numberInputs}/>
								   </dd>											
								</dl>										
								<dl className="pop-box-2">												
								<dt>文章内容：</dt>												
									<dd>													
								    	<textarea value={this.state.textareaValue} onChange={this.textareaValue.bind()} placeholder="请输入文章内容"></textarea>												
									</dd>											
								</dl>	
					   <ul className="up-img clearFix">
						{
								this.state.cover_image.map((item,index)=>{
								return(
									<ImagItem key={index} index={index} item={item} handleImg={this.handleImg.bind(this)} handleImgPath={this.handleImgPath.bind(this)} loadList={this.loadList.bind(this)}/>
								)
								})
						}
						{
								this.state.cover_imageBJ.map((item,index)=>{
								return(
									<ImagItem key={index} index={index} item={item} handleImg={this.handleImg.bind(this)} handleImgPath={this.handleImgPath.bind(this)} loadList={this.loadList.bind(this)}/>
								)
								})
						}																																		
						<Dropzone
							multiple={true}
							onDrop={this.chooseImage.bind(this)}
							className = 'choose-image'
							accept="image/jpeg, image/png"
						>												
						<li><label className="file-img">+</label></li>
						</Dropzone>											
				    	</ul>									
						</div>
						<div className="pop-btn">
							<Button className="btn btn-grey layui-layer-close" style={{height:'43px'}} loading={this.state.loadSaving} disabled={this.state.loadSaving||this.state.loadBtning}  onClick={()=>this.onSubmit(4)}>保存为草稿</Button>
							<Button className="btn add-book" style={{height:'43px'}} disabled={this.state.loadSaving||this.state.loadBtning} loading={this.state.loadBtning} onClick={()=>this.onSubmit(3)}>提交到审核</Button>
						</div>
					</div>

				</div>
			</Layer>	
			<a className="btn btn-blue add-new"  onClick={()=>this.showModal()}>发布</a>
		</div>
		)
	}
}
class MyArticle extends Component {
	constructor(args) {
		super();
		this.state = {
			activeIndex : 0,
			ArticleList :[],
			totalPage : 0 ,
			jumpPage: 1,
			loading:false,
			inputValue:'',
			textareaValue:'',
			modalShow:false,
			visibleDH:false,
			cover_image:[],
			essayId:'',
		    texts:"",
			loadBtning:false

		}
	}hideModelDH(){
			this.setState({
				visibleDH: false,
			});
	}
	ok(id){
		pub.loadBtning(this,true);
		fetch.cashEssay({essayId:id}).then((data)=>{
			if(data.result === 'RC100'){
				message.success(data.errMsg, 3)
				pub.jumpHistory.push("/PersonalCenter/MyArticleDetail/" +id)
			}else{
				message.error(data.errMsg, 3);
			}
			pub.loadBtning(this,false);
		}, (res) => {
			pub.reject(res);
			pub.loadBtning(this,false);
		})
	}
	clickArticle(item) {
		if (item.goodEssay === '1') {
			if (item.userEssayOperation.isBuy === 1) {
				pub.jumpHistory.push("/PersonalCenter/MyArticleDetail/" + item.essayId)
			} else {
				this.setState({
					visibleDH: true,
					essayId: item.essayId,
					studyIntegral: item.exchangeIntegral
				})
			}
		} else {
			pub.jumpHistory.push("/PersonalCenter/MyArticleDetail/" + item.essayId)
		}
	}
	myEssaylist(){
            pub.loading(this,true);
			fetch.myessayList({pageno:this.state.jumpPage,checkState:this.state.activeIndex===0?'':this.state.activeIndex}).then((data)=>{
				if(data.result==='RC100'){
					this.setState({
						ArticleList: data.essayList?data.essayList:[],
						totalPage: data.totalPage?data.totalPage:0
					})
				}else{
					message.error(data.errMsg, 3);
				}
				pub.loading(this,false);
			}, (res) => {
				pub.loading(this,false);
				pub.reject(res);
			})
	}
	componentWillMount() {
		this.myEssaylist();
	}
	jump(page) {
		this.setState({jumpPage: page},
		 function(){
          this.myEssaylist();
		 }
		);
	}
	change0Active(){
       this.setState({activeIndex:0},
	    function() { 
	      this.myEssaylist()
	     }
	   );
	}
	change4Active(){
       this.setState({activeIndex:4},
	    function() { 
	       this.myEssaylist()
	    }
	   );
	}
	change3Active(){
       this.setState({activeIndex:3},
		function() {
			this.myEssaylist();
		}
	   );
	}
	change1Active(){
       this.setState({activeIndex:1},
		function() {
			this.myEssaylist();
		}
	   );
	}
	change5Active(){
       this.setState({activeIndex:5},
	   function() {
			this.myEssaylist();
		}
	   );
	}
	change2Active(){
      this.setState({activeIndex:2},
	  function() {
			this.myEssaylist();
		}
	  );
	}
	editEssay(essayId){
			fetch.getSelectessay({essayId:essayId}).then((data)=>{
				this.setState({
					modalShow:true,
					inputValue: data.essay.essayTitle,
					textareaValue: data.essay.essayNote,
					cover_image:data.essay.essayPhotos,
					essayId:data.essay.essayId,
				    texts:"编辑文章"
				},()=>{
					this.myEssaylist();
				})
			}, (res) => {
				pub.reject(res);
			})
	}
	deleteArticle(essayId){
		this.setState({
			modalShow:false
		},()=>{
            pub.loading(this,true);
			let formData = new FormData();
	        formData.append('essayId',essayId);
			formData.append('operationState','D');
			fetch.insertorupdate(formData).then((data)=>{
					pub.loading(this,false);
					this.myEssaylist();
				}, (res) => {
					pub.loading(this,false);
					pub.reject(res);
				})
		   })	
	}
	loadList(){
		this.myEssaylist();
		this.setState({
			modalShow:false
		})
	}
	statusChange(){
		this.setState({
			modalShow:false
		})
	}
	render(){
		let ArticleList=this.state.ArticleList;
		return(
			<div>
				
				<div className="row">
					<div className="common-title">
						<div className="row btn-filter">
						<ul className="nav clearFix">
							<li className={this.state.activeIndex===0?"active":""} onClick={this.change0Active.bind(this)}><a>全部</a></li>
							<li className={this.state.activeIndex===4?"active":""} onClick={this.change4Active.bind(this)}><a>草稿</a></li>
							<li className={this.state.activeIndex===3?"active":""} onClick={this.change3Active.bind(this)}><a>审核中</a></li>
							<li className={this.state.activeIndex===1?"active":""} onClick={this.change1Active.bind(this)}><a>初审</a></li>
							<li className={this.state.activeIndex===5?"active":""} onClick={this.change5Active.bind(this)}><a>已通过</a></li>
							<li className={this.state.activeIndex===2?"active":""} onClick={this.change2Active.bind(this)}><a>未通过</a></li>
						</ul>
						{/*<a className="btn btn-blue release" onClick={()=>this.showModal()}>发布</a>*/}
						<AddMessge inputValue={this.state.inputValue} cover_imageBJ={this.state.cover_image} textareaValue={this.state.textareaValue} modalShow={this.state.modalShow} loadList={this.loadList.bind(this)} essayId={this.state.essayId} texts={this.state.texts}/>
					</div>
					</div>
					 <Spin spinning={this.state.loading} tip="加载列表中...">
					<div>
						{ArticleList.map((item,index)=>{
							return(
								<div key={index} className="panel-120 bg-FFFFFF box-shadow">
									<div className="article-list article-list-1">
										<p className="title">{item.essayTitle?item.essayTitle:''}</p>
										<p className="content shorthand">{item.essayNote?pub.subString(item.essayNote,100):'没有文字'}</p>
										<p className="time">{pub.formatTimestamp(item.updateTime?item.updateTime:'')}</p>
									</div>
									<div className="operate">
										<span className="red">{item.checkState==='5'?'已通过':(item.checkState==='2'?'未通过':(item.checkState==='4'?'':(item.checkState==='1'?'初审':'审核中')))}</span>
										<div className="operate-btn">
											<Link className="blue" onClick={() => this.clickArticle(item)}>查看</Link>
											{(item.checkState==='2'||item.checkState==='4')?<a className="blue-1" onClick={()=>this.editEssay(item.essayId)}>编辑</a>:null}
											{item.checkState==='2'||item.checkState==='4'?<a className="red" onClick={()=>this.deleteArticle(item.essayId)}>删除</a>:null}
										</div>
									</div>
									<Layer
										title="设置兑换积分"
										show={this.state.visibleDH}
										hide={(e) => { this.setState({ visibleDH: false }) }}
										width="400px"
										height="270px"
									>
										<div className="row">
											<div className="pop-box-1" style={{ textAlign: 'left' }}>
												<p style={{ textAlign: 'center' }}>您需要{this.state.studyIntegral}积分兑换该文章</p>
											</div>
											<div className="pop-btn">
												<Button onClick={() => this.hideModelDH()} className="btn btn-blue" loading={this.state.loadBtning} style={{ borderRadius: '5px', marginRight: '50px' }}>取消</Button>
												<Button className="btn btn-blue" style={{ borderRadius: '5px' }} loading={this.state.loadBtning} onClick={() => this.ok(this.state.essayId)}>确认</Button>
											</div>
										</div>
									</Layer>
								</div>
								)
						})}
			</div>
			 </Spin>
				</div>

				<div className="line"></div>
			    <Pages totalPage={this.state.totalPage} jump={this.jump.bind(this)}/>

			</div>
			)
	}
}
export default MyArticle;